package practice;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 10
 * 1,2,3
 * 0 1 1 1 0 0 0 0 0 0
 * 1 0 1 0 1 0 0 0 0 0
 * 1 1 0 1 0 0 0 0 0 0
 * 1 0 1 0 0 1 0 0 0 0
 * 0 1 0 0 0 0 1 0 0 0
 * 0 0 0 1 0 0 1 0 0 0
 * 0 0 0 0 1 1 0 1 1 0
 * 0 0 0 0 0 0 1 0 1 1
 * 0 0 0 0 0 0 1 1 0 1
 * 0 0 0 0 0 0 0 1 1 0
 */
public class PrecisionDetection {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            int n = Integer.parseInt(sc.nextLine());
            // 感染者
            List<Integer> confirmList = Arrays.stream(sc.nextLine().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            int[][] relation = new int[n][n];
            for (int i = 0; i < n; i++) {
                String[] row = sc.nextLine().split(" ");
                for (int j = 0; j < n; j++) {
                    relation[i][j] = Integer.parseInt(row[j]);
                }
            }

            int result = bfs(relation, confirmList);
            System.out.println(result);
        }
    }

    private static int bfs (int[][] relation,List<Integer> confirmList) {
        int n = relation.length;
        Set<Integer> needTestSet = new HashSet<>();
        for (Integer person: confirmList) {
            boolean[] visited = new boolean[n];
            Queue<Integer> queue = new LinkedList<>();
            queue.offer(person);
            visited[person] = true;

            while (!queue.isEmpty()) {
                Integer current = queue.poll();
                for (int i = 0; i < n; i++) {
                    // 有人和感染者有接触，并且未遍历
                    if (relation[current][i] == 1 && !visited[i]) {
                        // 入队接触者，并设置为已访问
                        queue.offer(i);
                        visited[i] = true;
                        needTestSet.add(i);
                    }
                }
            }
        }
        System.out.println(needTestSet);
        return needTestSet.size() - confirmList.size();
    }

    private static int dfs(int[][] relation,List<Integer> confirmList) {
        boolean[] visited = new boolean[relation.length];
        Set<Integer> needTestSet = new HashSet<>();
        for (Integer person: confirmList) {
            dfs(relation,visited,person);
            for (int i = 0; i < relation.length; i++) {
                if (visited[i]) {
                    needTestSet.add(i);
                }
            }
        }
        System.out.println(needTestSet);
        return needTestSet.size() - confirmList.size();
    }

    private static void dfs(int[][] relation,boolean[] visited,int person) {
        visited[person] = true;
        for (int i = 0; i < relation.length; i++) {
            if (relation[person][i] == 1 && !visited[i]) {
                dfs(relation,visited,i);
            }
        }
    }
}
